import Vue from 'vue'
import Vuex from 'vuex'
import router from './router'
import {HttpRequest} from './common/js/httpFun'
import {linklist} from './common/js/mockdata'
import {AlertDialog, setLocalstorage} from './common/js/common'
Vue.use(Vuex)
const state = {
  isLogin: false,
  userInfo: {
    'username': '',
    'mobile': '',
    'id': null
  },
  'cartList': []
}

// mutations are operations that actually mutates the state.
// each mutation handler gets the entire state tree as the
// first argument, followed by additional payload arguments.
// mutations must be synchronous and can be recorded by plugins
// for debugging purposes.
const mutations = {
  changeLogStatu (state, param) {
    localStorage.setItem('islogin', 'success')
    localStorage.setItem('userInfo', JSON.stringify(param.userInfo))
    state.isLogin = param.statu
    state.userInfo = param.userInfo
    router.go(-1)
  },
  addGoodsToCart (state, param) {
    setLocalstorage('cartlist', param.cartlist)
    state.cartlist = param.cartlist
    router.push({name: 'placeOrder'})
  }
}

// actions are functions that causes side effects and can involve
// asynchronous operations.
const actions = {
  changeLogStatu ({commit, state}, userInfo) {
    let result = HttpRequest(linklist.loginUrl)
    result.then((response) => {
      if (response.status === 200) {
        let userInfo = response.body
        /* 保存用户信息 */
        commit('changeLogStatu', {
          statu: true,
          userInfo: userInfo
        })
      }
      else {
        AlertDialog('错误', '验证码不正确')
      }
    }, (response) => {
      // ...
    }).catch((response) => {
      // ...
    })
  }
}

// getters are functions
const getters = {}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})
